<?php

namespace App\Models;

use App\Models\Common\Constant;
use App\Models\ResourceModel\TasksModel;
use App\Models\ResourceModel\TasksSon;
use App\Models\ResourceModel\Users;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class TaskModel extends BaseModel
{
    //
    protected $table = 'tasks';

    const UPDATED_AT = null;
    const CREATED_AT = null;
    public $guarded = [];
    protected $userModel;
    protected $tasksSonModel;
    protected $tasksModel;

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->tasksSonModel = new TasksSon();
        $this->tasksModel = new TasksModel();
        $this->userModel = new Users();
        $this->tasksModel = new TasksModel();
    }
    public function file_upload(){
        $files = isset($_FILES['file']) ? $_FILES['file'] : null;
        if(!empty($files)){
            $filename = $files['name'];
            $tmp_file = $files['tmp_name'];
            $error = $files['error'];
            if ($error == 0) {
                $save = move_uploaded_file($tmp_file, $_SERVER['DOCUMENT_ROOT'] . '/task_img/' . $filename);
                if ($save) {
                    $file_url = '/task_img/' . $filename;
                    $file_name = $filename;
                } else {
                    return ['type' => 'fail', 'msg' => '上传失败','data'=>''];
                }
            }
            if(isset($file_url)){
                return ['type' => 'success', 'msg' => '上传成功','data'=>['name'=>$file_name,'url'=>$file_url]];
            }else{
                return ['type' => 'fail', 'msg' => '上传失败','data'=>''];
            }
        }else{
            return ['type'=>'fail','msg'=>'上传失败，没有获取到文件','data'=>''];
        }
    }

    //审核建议
    public function examine_advice($params){
        $task_id = $params['task_id'];
        if(isset($params['ext_id'])){
            if($params['task_class']==2||$params['task_class']==3||$params['task_class']==4){
                    $detail = DB::table('amazon_buhuo_detail')->where('request_id',$params['ext_id'])->select('request_num','sku')->get();
                    $detail = json_decode(json_encode($detail),true);
                    $startTimeTwo = date('Y-m-d 00:00:00', strtotime('-15 days'));
                    $endTime = date('Y-m-d 00:00:00', strtotime('-1 days'));
                    $skulist = array_column($detail,'sku');
                    $inventory = DB::table('product_detail')->whereIn('sellersku',$skulist)->select('in_stock_num','in_bound_num','transfer_num','sellersku')->get();
                    $kucun = [];
                    foreach ($inventory as $inven){
                        $kucun[$inven->sellersku] = $inven->in_stock_num + $inven->in_bound_num + $inven->transfer_num;
                    }
                    if(!empty($detail)){
                        $num = [];
                        $res = [];
                        $skunum = 0;//超出建议的sku数量
                        foreach ($detail as $k=>$d){
                            $num[$k] = $d['request_num']; // 请求数量
                            $order_num = DB::table('amazon_order_item')
                                ->where('seller_sku',$d['sku'])
                                ->where('order_status','!=','Canceled')
                                ->whereBetween('amazon_time', [$startTimeTwo, $endTime])
                                ->sum('quantity_ordered');
                            $day_num = $order_num/14;//日销
                            $this_kucun = isset($kucun[$d['sku']])? $kucun[$d['sku']] : 0;
                            //建议补货数量
                            $advice = $day_num*90-$this_kucun > 0 ? $day_num*90-$this_kucun : 0;
                            if($advice<$num[$k]){
                                $res[] = $num[$k]-$advice;
                                $skunum++;
                            }
                        }
                        $resSum = array_sum($res);//超出建议的补货数量合计
                        $resSum = round($resSum);
                        if($resSum>0){
                            $result['type'] = 2;//异常
                            $result['data'] = '本次补货有'.$skunum.'个sku，补货数量超出，共计超出'.$resSum.'个，建议查看明细调整数量';
                        }else{
                            $result['type'] = 1;//合理
                            $result['data'] = '补货合理,无建议';
                        }
                    }
                    $resSum = array_sum($res);//超出建议的补货数量合计
                    $resSum = round($resSum);
                    if($resSum>0){
                        $result['type'] = 2;//异常
                        $result['data'] = '本次补货有'.$skunum.'个sku，补货数量超出，共计超出'.$resSum.'个，建议查看明细调整数量';
                    }else{
                        $result['type'] = 1;//合理
                        $result['data'] = '补货合理,无建议';
                    }
                }else{
                    $result['type'] = 0;//无
                }
            }else{
                $result['type'] = 0;//无

            }
        return $result;
    }


    public function reassignEnforcer($params)
    {
        try {
            $this->_filterReassignEnforcerParams($params);
            $taskSon = DB::table('tasks_son')->where('id', $params['id'])->first();

            if (empty($taskSon)){
                throw new \Exception('为查询到节点任务信息！');
            }
            DB::beginTransaction();
            $error = '';
            foreach ($params['user_id'] as $userId){
                $save = [
                    'task_id' => $taskSon->task_id,
                    'tasks_node_id' => $taskSon->tasks_node_id,
                    'f_id' => $taskSon->f_id,
                    'task' => $taskSon->task,
                    'user_id' => $userId,
                    'day_yj' => $taskSon->day_yj,
                    'state' => 1,
                    'feedback_type' => $taskSon->feedback_type,
                    'feedback_content' => $taskSon->feedback_content,
                    'feedback_content2' => $taskSon->feedback_content2,
                    'create_time' => date('Y-m-d H:i:s')
                ];
                $insertId = DB::table('tasks_son')->insertGetId($save);
                if (empty($insertId)){
                    $username = $this->GetUsers($userId)['account'] ?? '';
                    $error .= '任务指派给'.$username.'失败！';
                }
            }
            if (!empty($error)){
                throw new \Exception($error);
            }
            DB::table('tasks_son')->where('id', $params['id'])->delete();

            DB::commit();

            return ['code' => 200, 'msg' => '重新指派成功！'];
        }catch (\Exception $e){
            DB::rollback();
            return ['code' => 500, 'msg' => '重新指派失败！错误原因:'.$e->getMessage()];
        }
    }

    private function _filterReassignEnforcerParams($params)
    {
        if (isset($params['id']) && !empty($params['id'])){
            $tasksSonMdl = $this->tasksSonModel::query()
                ->where('Id', $params['id'])
                ->first();
            if (empty($tasksSonMdl)){
                throw new \Exception('未查询到该任务节点');
            }
            if (!in_array($tasksSonMdl->state, [1, 2])){
                throw new \Exception('该任务节点非未开始/进行中状态，不予重新指派执行人！');
            }
        }else{
            throw new \Exception('未给定任务节点标识！');
        }

        if (isset($params['user_id']) && !empty($params['user_id'])){
            foreach ($params['user_id'] as $userId){
                $user = $this->GetUsers($userId);
                if (empty($user)){
                    throw new \Exception('未查询到该执行人信息！');
                }
            }
        }else{
            throw new \Exception('未给定执行人标识！');
        }

        return true;
    }

    public function getBuhuoRequestTaskInfo($params)
    {
        try {
            if (!isset($params['request_id']) || empty($params['request_id'])){
//                throw new \Exception("未给定计划请求标识！
                $data = [
                    'is_update' => 0,
                    'task_id' => 0
                ];
                return ['code' => 200, 'msg' => '未给定计划请求标识', 'data' => $data];
            }

            $requestId = '"request_id":"'.$params['request_id'].'"';
            $_requestId = '"request_id":'.$params['request_id'];
            $taskMdl = $this->tasksModel::query()
                ->where('ext', 'like', '%'.$requestId.'%')
                ->orWhere('ext', 'like', '%'.$_requestId.'%')
                ->orderBy('create_time', 'desc')
                ->first();
            $data = [];
            if (empty($taskMdl)){
                $data = [
                    'is_update' => 0,
                    'task_id' => 0
                ];
            }else{
                $data = [
                    'is_update' => 1,
                    'task_id' => $taskMdl->Id
                ];

            }

            return ['code' => 200, 'msg' => '获取成功！', 'data' => $data];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage()];
        }
    }

    public function getHistoryTaskInfo($params)
    {
        try {
            $data = [
                'is_update' => 0,
                'task_id' => 0
            ];
            if (!isset($params['type']) || empty($params['type'])){
                $data = [
                    'is_update' => 0,
                    'task_id' => 0
                ];
                return ['code' => 200, 'msg' => '未给定任务类型', 'data' => $data];
            }
            if (!isset($params['id']) || empty($params['id'])){
                $data = [
                    'is_update' => 0,
                    'task_id' => 0
                ];
                return ['code' => 200, 'msg' => '未给定唯一标识', 'data' => $data];
            }
            if (!isset($params['class_id']) || empty($params['class_id'])){
                $data = [
                    'is_update' => 0,
                    'task_id' => 0
                ];
                return ['code' => 200, 'msg' => '未给定任务分类标识', 'data' => $data];
            }

            $id = '';
            $_id = '';
            switch ($params['type']){
                case 1:
                    // 补货请求任务
                    $id = '"request_id":"'.$params['id'].'"';
                    $_id = '"request_id":'.$params['id'];
                    break;
                case 2:
                    // 生产下单任务
                    $id = '"contract_no":"'.$params['id'].'"';
                    $_id = '"contract_no":'.$params['id'];
                    break;
                case 3:
                    // 预付账单
                    $id = '"bill_no":"'.$params['id'].'"';
                    $_id = '"bill_no":'.$params['id'];
                    break;
                default:
                    $data = [
                        'is_update' => 0,
                        'task_id' => 0
                    ];
                    if (!isset($params['task_id']) || empty($params['task_id'])){
                        throw new \Exception("未给定任务号标识！");
                    }
                    $taksMdl = db::table('tasks as a')
                        ->leftJoin('task_class as b', 'a.class_id', '=', 'b.id')
                        ->where('a.Id', $params['task_id'])
                        ->where('a.class_id', $params['class_id'])
                        ->orderBy('a.create_time', 'DESC')
                        ->first();
                    if (!empty($taksMdl)){
                        if ($taksMdl->is_deleted == 0){
                            throw new \Exception($taksMdl->title."任务不可重发！");
                        }
                    }else{
                        $data = [
                            'is_update' => 0,
                            'task_id' => 0
                        ];
                    }

                    $data = [
                        'is_update' => 1,
                        'task_id' => $taksMdl->Id
                    ];

                    return ['code' => 200, 'msg' => '获取成功！', 'data' => $data];
            }

            $taskMdl = db::table('tasks')
                ->where('class_id', $params['class_id'])
                ->where('ext', 'like', '%'.$id.'%')
                ->orWhere('ext', 'like', '%'.$_id.'%')
                ->orderBy('create_time', 'desc')
                ->first();
            if (empty($taskMdl)){
                $data = [
                    'is_update' => 0,
                    'task_id' => 0
                ];
            }else{
                $data = [
                    'is_update' => 1,
                    'task_id' => $taskMdl->Id
                ];

            }

            return ['code' => 200, 'msg' => '获取成功！', 'data' => $data];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage()];
        }
    }

    public function AddTaskUser($params){

        $insert['user_id'] = $params['user_id'];
        $insert['task_id'] = $params['task_id'];
        $insert['is_examine'] = 2;
        $insert['state'] = 1;
        db::table('tasks_examine')->insert($insert);
        return ['type'=>'success','msg'=>'添加成功'];
    }

    public function CopyTaskM($params){
        $id = $params['id'];
        $task = db::table('tasks')->where('Id',$id)->first();
        if(!$task){
            return ['type'=>'fail','msg'=>'无此任务'];
        }
        if($task->class_id==2||$task->class_id==3||$task->class_id==4||$task->class_id==19){
            return ['type'=>'fail','msg'=>'补货任务及生产下单不允许复制'];
        }
        $task = json_decode(json_encode($task),true);
        unset($task['Id']);
        $new_id = db::table('tasks')->insertGetId($task);

        $ex = db::table('tasks_examine')->where('task_id',$id)->get();
        foreach ($ex as $v) {
            # code...
            $ex_v = json_decode(json_encode($v),true);
            unset($ex_v['Id']);
            $ex_v['task_id'] = $new_id;
            db::table('tasks_examine')->insert($ex_v);
        }
        return ['type'=>'success','msg'=>'拷贝成功'];
    }

    /**
     * @Desc:仓库时效表
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/4/24 16:48
     */
    public function getWarehouseTimeTable($params)
    {
        // 获取补货计划任务
        $task = DB::table('tasks')
            ->whereIn('state', [1, 3, 4, 5])
            ->where('type', 1)
            ->whereIn('class_id', [2, 3, 4])
            ->where('is_deleted', 0)
            ->whereBetween('create_time', ['2023-03-01', date('Y-m-d')]);

        if (isset($params['task_id']) && !empty($params['task_id'])){
            $taskId = explode(',', $params['task_id']);
            $task = $task->whereIn('Id', $taskId);
        }
        // 过滤仓库 ps:根据模板过滤 2：云仓 3：同安仓 4：泉州仓
        if (isset($params['class_id']) && !empty($params['class_id'])) {
            $task = $task->where('class_id', $params['class_id']);
        }
        // 过滤负责人
        if (isset($params['user_fz_id']) && !empty($params['user_fz_id'])) {
            $task = $task->where('user_fz', $params['user_fz_id']);
        }
        // 过滤任务创建时间
        if (isset($params['created_at'][0]) && !empty($params['created_at'][0])) {
            $params['created_at'][0] = $params['created_at'][0].' 00:00:00';
            $task = $task->where('create_time', '>',$params['created_at'][0]);
        }
        // 过滤任务创建时间
        if (isset($params['created_at'][1]) && !empty($params['created_at'][1])) {
            $params['created_at'][1] = $params['created_at'][1].' 23:59:59';
            $task = $task->where('create_time', '<=',$params['created_at'][1]);
        }
        // 数据长度
        $count = $task->count();
        if ((isset($params['limit']) || isset($params['page'])) && (!isset($params['post_type']) || $params['post_type'] != 2)){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $task = $task->limit($limit)
                ->offset($offsetNum);
        }
        $task = $task
            ->orderBy('create_time', 'DESC')
            ->get();
        if ($task->isEmpty()){
            $task = [];
            $count = 0;
            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count]];
        }else{

            // 获取任务对应节点信息
            $taskIds = array_column($task->toArray(), 'Id');
            $taskNode = DB::table('tasks_node as a')
                ->leftJoin('tasks_son as b', 'a.Id', '=', 'b.tasks_node_id')
                ->whereIn('a.task_id', $taskIds)
                ->get(['a.*', 'b.time_end_sj', 'b.time_state as son_time_state']);
            // 处理数据
            $requestIds = [];
            foreach ($task as $t){
                $ext = json_decode($t->ext, true);
                $t->request_link = $ext['request_link'] ?? '';
                $t->request_id = $ext['request_id'] ?? 0;
                $t->sales_start_time = $ext['start_time'] ?? '';
//            $t->end_time = $ext['end_time']
                $requestIds[] = $t->request_id;
                $t->warehouse_name = Constant::BUHUO_TASK_SEND_WAREHOUSE_TYPE[$t->class_id] ?? ''; // 发货仓库
                $user = $this->GetUsers($t->user_fz);
                $t->user_fz_name = $user['account'] ?? '';
                foreach ($taskNode as $n){
                    if ($t->Id == $n->task_id){
                        switch ($n->name){
                            case '备货装箱':
                                if ($n->state == 1){
                                    $t->stock_and_pack = '未开始';
                                    $t->stock_and_pack_time = 0;
                                    $t->stock_and_pack_operate_time = 0;
                                }else if ($n->state == 2){
                                    $t->stock_and_pack = '进行中';
                                    $t->stock_and_pack_time = 0;
                                    $t->stock_and_pack_operate_time = 0;
                                }else if ($n->state == 3){
                                    $t->stock_and_pack = '已完成';
                                    if (empty($n->time_end) || empty($n->time_state) || $n->time_end <= '1970-01-01 08:00:00' || $n->time_state <= '1970-01-01 08:00:00'){
                                        // 日期错误
                                        $t->stock_and_pack_time = 0;
                                    }else{
                                        $t->stock_and_pack_time = abs(strtotime($n->time_end)-strtotime($n->time_state));
                                    }

                                    if (empty($n->time_end_sj) || empty($n->son_time_state) || $n->time_end_sj == '0000-00-00 00:00:00' || $n->son_time_state == '0000-00-00 00:00:00'){
                                        $t->stock_and_pack_operate_time = 0;
                                    }else{
                                        $t->stock_and_pack_operate_time = abs(strtotime($n->time_end_sj)-strtotime($n->son_time_state));
                                    }
                                }
                                $t->stock_and_pack_time = $this->timestampConversion($t->stock_and_pack_time);
                                $t->stock_and_pack_operate_time = $this->timestampConversion($t->stock_and_pack_operate_time);
                                break;
                            case '创货件':
                                if ($n->state == 1){
                                    $t->create_shipment = '未开始';
                                    $t->create_shipment_time = 0;
                                }else if ($n->state == 2){
                                    $t->create_shipment = '进行中';
                                    $t->create_shipment_time = 0;
                                }else if ($n->state == 3){
                                    $t->create_shipment = '已完成';
                                    if (empty($n->time_end) || empty($n->time_state) || $n->time_end <= '1970-01-01 08:00:00' || $n->time_state <= '1970-01-01 08:00:00'){
                                        // 日期错误
                                        $t->create_shipment_time = 0;
                                    }else{
                                        $t->create_shipment_time = abs(strtotime($n->time_end)-strtotime($n->time_state));
                                    }
                                }
                                $t->create_shipment_time = $this->timestampConversion($t->create_shipment_time);
                                break;
                            case '确认出库':
                                if ($n->state == 1){
                                    $t->confirm_out_bound = '未开始';
                                    $t->confirm_out_bound_time = 0;
                                }else if ($n->state == 2){
                                    $t->confirm_out_bound = '进行中';
                                    $t->confirm_out_bound_time = 0;
                                }else if ($n->state == 3){
                                    $t->confirm_out_bound = '已完成';
                                    if (empty($n->time_end) || empty($n->time_state) || $n->time_end <= '1970-01-01 08:00:00' || $n->time_state <= '1970-01-01 08:00:00'){
                                        // 日期错误
                                        $t->confirm_out_bound_time = 0;
                                    }else{
                                        $t->confirm_out_bound_time = abs(strtotime($n->time_end)-strtotime($n->time_state));
                                    }
                                }
                                $t->confirm_out_bound_time = $this->timestampConversion($t->confirm_out_bound_time);
                                break;
                            case '发货':
                                if ($n->state == 1){
                                    $t->send_out_goods = '未开始';
                                    $t->send_out_goods_time = 0;
                                }else if ($n->state == 2){
                                    $t->send_out_goods = '进行中';
                                    $t->send_out_goods_time = 0;
                                }else if ($n->state == 3){
                                    $t->send_out_goods = '已完成';
                                    if (empty($n->time_end) || empty($n->time_state) || $n->time_end <= '1970-01-01 08:00:00' || $n->time_state <= '1970-01-01 08:00:00'){
                                        // 日期错误
                                        $t->send_out_goods_time = 0;
                                    }else{
                                        $t->send_out_goods_time = abs(strtotime($n->time_end)-strtotime($n->time_state));
                                    }
                                }
                                $t->send_out_goods_time = $this->timestampConversion($t->send_out_goods_time);
                                break;
                            default:
                                break;
                        }
                    }
                }
            }

            // 获取补货数据
            $buhuoDetailMdl = DB::table('amazon_buhuo_detail')
                ->whereIn('request_id', $requestIds)
                ->get();
            $buhuoDetail = [];
            foreach ($buhuoDetailMdl as $v){
                if (array_key_exists($v->request_id, $buhuoDetail)){
                    $buhuoDetail[$v->request_id] += $v->request_num;
                }else{
                    $buhuoDetail[$v->request_id] = $v->request_num;
                }
            }
            $buhuoBoxMdl = DB::table('amazon_box_data')
                ->whereIn('request_id', $requestIds)
                ->get();
            $buhuoBox = [];
            foreach ($buhuoBoxMdl as $v){
                if (array_key_exists($v->request_id, $buhuoBox)){
                    $buhuoBox[$v->request_id] += $v->box_num;
                }else{
                    $buhuoBox[$v->request_id] = $v->box_num;
                }
            }
            foreach ($task as $t){
                $t->total_request_num = $buhuoDetail[$t->request_id] ?? 0;
                $t->total_shippent_num = $buhuoBox[$t->request_id] ?? 0;
            }
            $task = $task->toArray();
            if (isset($params['post_type']) && $params['post_type'] == 2){
                $p['title']='仓库时效表导出'.time();
                $title = [
                    'Id'  => '任务Id',
                    'name'  => '任务名称',
                    'user_fz_name' => '负责人',
                    'warehouse_name'     => '发货仓库',
                    'request_id'            => '补货请求ID',
                    'stock_and_pack'            => '备货装箱状态',
                    'stock_and_pack_time'       => '备货装箱时效',
                    'stock_and_pack_operate_time'       => '备货装箱操作时效',
                    'create_shipment'    => '创货件状态',
                    'create_shipment_time'      => '创货件时效',
                    'confirm_out_bound'     => '确认出库状态',
                    'confirm_out_bound_time'     => '确认出库时效',
                    'send_out_goods'     => '发货状态',
                    'send_out_goods_time'     => '发货时效',
                    'total_request_num'     => '补货请求总数',
                    'total_shippent_num'     => '实际发货总数',
                    'create_time'     => '任务创建时间',
                ];

                $p['title_list']  = $title;
                $p['data'] =  $task;
                $userId = 1;
                if (!isset($params['user_id']) || empty($params['user_id'])){
                    if (isset($params['token']) && !empty($params['token'])){
                        $users = db::table('users')->where('token',$params['token'])->first();
                        if($users){
                            $userId = $users->Id;
                        }else{
                            $userId = 0;
                        }
                    }
                }
                $find_user_id = $userId;
                $p['user_id'] = $find_user_id;
                $p['type'] = '仓库时效表导出';

                $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
                try {
                    $job::runJob($p);
                    return ['code' => 200, 'msg' => '加入队列成功！'];
                } catch(\Exception $e){
                    return ['code' => 500, 'msg' => '加入队列失败！'.$e->getMessage()];
                }
            }

            $list = $task;
            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list]];
        }
    }

    public function getWarehouseTimeTableStatistics($params)
    {
        // 获取补货计划任务
        $task = DB::table('tasks')
            ->whereIn('state', [1, 3, 4, 5])
            ->where('type', 1)
            ->whereIn('class_id', [2, 3, 4])
            ->where('is_deleted', 0)
            ->whereBetween('create_time', ['2023-03-01', date('Y-m-d')]);

        if (isset($params['task_id']) && !empty($params['task_id'])){
            $taskId = explode(',', $params['task_id']);
            $task = $task->whereIn('Id', $taskId);
        }
        // 过滤仓库 ps:根据模板过滤 2：云仓 3：同安仓 4：泉州仓
        if (isset($params['class_id']) && !empty($params['class_id'])) {
            $task = $task->where('class_id', $params['class_id']);
        }
        // 过滤负责人
        if (isset($params['user_fz_id']) && !empty($params['user_fz_id'])) {
            $task = $task->where('user_fz', $params['user_fz_id']);
        }
        // 过滤任务创建时间
        if (isset($params['created_at'][0]) && !empty($params['created_at'][0])) {
            $params['created_at'][0] = $params['created_at'][0].' 00:00:00';
            $task = $task->where('create_time', '>',$params['created_at'][0]);
        }
        // 过滤任务创建时间
        if (isset($params['created_at'][1]) && !empty($params['created_at'][1])) {
            $params['created_at'][1] = $params['created_at'][1].' 23:59:59';
            $task = $task->where('create_time', '<=',$params['created_at'][1]);
        }
        $task = $task
            ->orderBy('create_time', 'DESC')
            ->get();
        if ($task->isEmpty()){
            $task = [];
            $count = 0;
            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count]];
        }else{
            // 数据长度
            $count = $task->count();
            // 获取任务对应节点信息
            $taskIds = array_column($task->toArray(), 'Id');
            $taskNode = DB::table('tasks_node as a')
                ->leftJoin('tasks_son as b', 'a.Id', '=', 'b.tasks_node_id')
                ->whereIn('a.task_id', $taskIds)
                ->get(['a.*', 'b.time_end_sj', 'b.time_state as son_time_state']);
            // 处理数据
            $totalStockAndPackTime = 0;
            $totalCreateShipmentTime = 0;
            $totalConfirmOutBoundTime = 0;
            $totalSendOutGoodsTime = 0;
            $totalStockAndPackOperationTime = 0;
            $requestIds = [];
            foreach ($task as $t){
                $ext = json_decode($t->ext, true);
                $t->request_link = $ext['request_link'] ?? '';
                $t->request_id = $ext['request_id'] ?? 0;
                $t->sales_start_time = $ext['start_time'] ?? '';
//            $t->end_time = $ext['end_time']
                $requestIds[] = $t->request_id;
                $t->warehouse_name = Constant::BUHUO_TASK_SEND_WAREHOUSE_TYPE[$t->class_id] ?? ''; // 发货仓库
                $user = $this->GetUsers($t->user_fz);
                $t->user_fz_name = $user['account'] ?? '';
                foreach ($taskNode as $n){
                    if ($t->Id == $n->task_id){
                        switch ($n->name){
                            case '备货装箱':
                                if ($n->state == 1){
                                    $t->stock_and_pack = '未开始';
                                    $t->stock_and_pack_time = 0;
                                    $t->stock_and_pack_operate_time = 0;
                                }else if ($n->state == 2){
                                    $t->stock_and_pack = '进行中';
                                    $t->stock_and_pack_time = 0;
                                    $t->stock_and_pack_operate_time = 0;
                                }else if ($n->state == 3){
                                    $t->stock_and_pack = '已完成';
                                    if (empty($n->time_end) || empty($n->time_state) || $n->time_end <= '1970-01-01 08:00:00' || $n->time_state <= '1970-01-01 08:00:00'){
                                        // 日期错误
                                        $t->stock_and_pack_time = 0;
                                    }else{
                                        $t->stock_and_pack_time = abs(strtotime($n->time_end)-strtotime($n->time_state));
                                    }

                                    if (empty($n->time_end_sj) || empty($n->son_time_state) || $n->time_end_sj == '0000-00-00 00:00:00' || $n->son_time_state == '0000-00-00 00:00:00'){
                                        $t->stock_and_pack_operate_time = 0;
                                    }else{
                                        $t->stock_and_pack_operate_time = abs(strtotime($n->time_end_sj)-strtotime($n->son_time_state));
                                    }
                                }
                                $totalStockAndPackTime += $t->stock_and_pack_time;
                                $totalStockAndPackOperationTime += $t->stock_and_pack_operate_time;
                                $t->stock_and_pack_time = $this->timestampConversion($t->stock_and_pack_time);
                                $t->stock_and_pack_operate_time = $this->timestampConversion($t->stock_and_pack_operate_time);
                                break;
                            case '创货件':
                                if ($n->state == 1){
                                    $t->create_shipment = '未开始';
                                    $t->create_shipment_time = 0;
                                }else if ($n->state == 2){
                                    $t->create_shipment = '进行中';
                                    $t->create_shipment_time = 0;
                                }else if ($n->state == 3){
                                    $t->create_shipment = '已完成';
                                    if (empty($n->time_end) || empty($n->time_state) || $n->time_end <= '1970-01-01 08:00:00' || $n->time_state <= '1970-01-01 08:00:00'){
                                        // 日期错误
                                        $t->create_shipment_time = 0;
                                    }else{
                                        $t->create_shipment_time = abs(strtotime($n->time_end)-strtotime($n->time_state));
                                    }
                                }
                                $totalCreateShipmentTime += $t->create_shipment_time;
                                $t->create_shipment_time = $this->timestampConversion($t->create_shipment_time);
                                break;
                            case '确认出库':
                                if ($n->state == 1){
                                    $t->confirm_out_bound = '未开始';
                                    $t->confirm_out_bound_time = 0;
                                }else if ($n->state == 2){
                                    $t->confirm_out_bound = '进行中';
                                    $t->confirm_out_bound_time = 0;
                                }else if ($n->state == 3){
                                    $t->confirm_out_bound = '已完成';
                                    if (empty($n->time_end) || empty($n->time_state) || $n->time_end <= '1970-01-01 08:00:00' || $n->time_state <= '1970-01-01 08:00:00'){
                                        // 日期错误
                                        $t->confirm_out_bound_time = 0;
                                    }else{
                                        $t->confirm_out_bound_time = abs(strtotime($n->time_end)-strtotime($n->time_state));
                                    }
                                }
                                $totalConfirmOutBoundTime += $t->confirm_out_bound_time;
                                $t->confirm_out_bound_time = $this->timestampConversion($t->confirm_out_bound_time);
                                break;
                            case '发货':
                                if ($n->state == 1){
                                    $t->send_out_goods = '未开始';
                                    $t->send_out_goods_time = 0;
                                }else if ($n->state == 2){
                                    $t->send_out_goods = '进行中';
                                    $t->send_out_goods_time = 0;
                                }else if ($n->state == 3){
                                    $t->send_out_goods = '已完成';
                                    if (empty($n->time_end) || empty($n->time_state) || $n->time_end <= '1970-01-01 08:00:00' || $n->time_state <= '1970-01-01 08:00:00'){
                                        // 日期错误
                                        $t->send_out_goods_time = 0;
                                    }else{
                                        $t->send_out_goods_time = abs(strtotime($n->time_end)-strtotime($n->time_state));
                                    }
                                }
                                $totalSendOutGoodsTime += $t->send_out_goods_time;
                                $t->send_out_goods_time = $this->timestampConversion($t->send_out_goods_time);
                                break;
                            default:
                                break;
                        }
                    }
                }
            }

            // 获取补货数据
            $buhuoDetailMdl = DB::table('amazon_buhuo_detail')
                ->whereIn('request_id', $requestIds)
                ->get();
            $buhuoDetail = [];
            foreach ($buhuoDetailMdl as $v){
                if (array_key_exists($v->request_id, $buhuoDetail)){
                    $buhuoDetail[$v->request_id] += $v->request_num;
                }else{
                    $buhuoDetail[$v->request_id] = $v->request_num;
                }
            }
            $buhuoBoxMdl = DB::table('amazon_box_data')
                ->whereIn('request_id', $requestIds)
                ->get();
            $buhuoBox = [];
            foreach ($buhuoBoxMdl as $v){
                if (array_key_exists($v->request_id, $buhuoBox)){
                    $buhuoBox[$v->request_id] += $v->box_num;
                }else{
                    $buhuoBox[$v->request_id] = $v->box_num;
                }
            }
            foreach ($task as $t){
                $t->total_request_num = $buhuoDetail[$t->request_id] ?? 0;
                $t->total_shippent_num = $buhuoBox[$t->request_id] ?? 0;
            }
            $task = $task->toArray();

            $list = $task;
            // 平均任务时长
            $averageStockAndPackTime = $this->timestampConversion($totalStockAndPackTime/$count);
            $averageCreateShipmentTime = $this->timestampConversion($totalCreateShipmentTime/$count);
            $averageConfirmOutBoundTime = $this->timestampConversion($totalConfirmOutBoundTime/$count);
            $averageSendOutGoodsTime = $this->timestampConversion($totalSendOutGoodsTime/$count);
            $averageStockAndPackOperationTime = $this->timestampConversion($totalStockAndPackOperationTime/$count);
            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list, 'average_stock_and_pack_time' => $averageStockAndPackTime, 'average_create_shipment_time' => $averageCreateShipmentTime, 'average_confirm_out_bound_time' => $averageConfirmOutBoundTime, 'average_send_out_goods_time' => $averageSendOutGoodsTime, 'average_stock_and_pack_operation_time' => $averageStockAndPackOperationTime]];
        }
    }

    public function getTaskNewAllList($params)
    {
        try {
            if (!isset($params['scene']) || empty($params['scene'])){
                throw new \Exception('未给定场景值！');
            }
            switch ($params['scene']){
                case 1:
                    // 获取任务评论
                    $taskNewMdl = db::table('tasks_news');
                    if (isset($params['task_id']) && !empty($params['task_id'])){
                        $taskNewMdl = $taskNewMdl->where('task_id', $params['task_id']);
                    }
                    if (isset($params['user_fs']) && !empty($params['user_fs'])){
                        $taskNewMdl = $taskNewMdl->where('user_fs', $params['user_fs']);
                    }
                    if (isset($params['user_js']) && !empty($params['user_js'])){
                        $taskNewMdl = $taskNewMdl->where('user_js', 'like', '%'.$params['user_js'].'%');
                    }
                    if (isset($params['msg_type']) && !empty($params['msg_type'])){
                        $taskNewMdl = $taskNewMdl->where('msg_type', $params['msg_type']);
                    }
                    if (isset($params['create_time']) && !empty($params['create_time'])){
                        $taskNewMdl = $taskNewMdl->whereBetween('create_time', $params['create_time']);
                    }
                    $count = $taskNewMdl->count();
                    if (isset($params['limit']) && isset($params['page'])){
                        $limit = $params['limit'] ?? 30;
                        $page = $params['page'] ?? 1;
                        $offset = $limit * ($page-1);
                        $taskNewMdl = $taskNewMdl->limit($limit)->offset($offset);
                    }
                    $taskNewMdl = $taskNewMdl->orderBy('create_time', 'DESC')->get();
                    foreach ($taskNewMdl as $item){
                        $item->user_fs_name = $this->GetUsers($item->user_fs)['account'] ?? '';
                        if ($item->user_js){
                            $userJs = explode(',', $item->user_js);
                            $userJsName = [];
                            foreach ($userJs as $uid){
                                $userJsName[] = $this->GetUsers($uid)['account'] ?? '';
                            }
                            $item->user_js_name = $userJsName;
                        }else{
                            $item->user_js = [];
                            $item->user_js_name = [];
                        }
                        $item->file = json_decode($item->file, true) ?? [];
                        $item->img = json_decode($item->img, true) ?? [];
                        $item->msg_type_name = Constant::TASKS_NEWS_MSG_TYPE_NAME[$item->msg_type] ?? '';
                    }
                    $list = $taskNewMdl;
                    break;
                case 2:
                    // 审核意见
                    $taskNewMdl = db::table('tasks_examine')->whereNotNull('desc');
                    if (isset($params['task_id']) && !empty($params['task_id'])){
                        $taskNewMdl = $taskNewMdl->where('task_id', $params['task_id']);
                    }
                    if (isset($params['user_id']) && !empty($params['user_id'])){
                        $taskNewMdl = $taskNewMdl->where('user_id', $params['user_id']);
                    }
                    if (isset($params['time_sh']) && !empty($params['time_sh'])){
                        $taskNewMdl = $taskNewMdl->whereBetween('time_sh', $params['time_sh']);
                    }
                    $count = $taskNewMdl->count();
                    if (isset($params['limit']) && isset($params['page'])){
                        $limit = $params['limit'] ?? 30;
                        $page = $params['page'] ?? 1;
                        $offset = $limit * ($page-1);
                        $taskNewMdl = $taskNewMdl->limit($limit)->offset($offset);
                    }
                    $taskNewMdl = $taskNewMdl->orderBy('time_sh', 'DESC')->get();
                    foreach ($taskNewMdl as $item){
                        $item->user_name = $this->GetUsers($item->user_id)['account'] ?? '';
                    }
                    $list = $taskNewMdl;
                    break;
                case 3:
                    // 任务反馈
                    $taskNewMdl = db::table('tasks_son')->whereNotNull('feedback_type');
                    if (isset($params['task_id']) && !empty($params['task_id'])){
                        $taskNewMdl = $taskNewMdl->where('task_id', $params['task_id']);
                    }
                    if (isset($params['user_id']) && !empty($params['user_id'])){
                        $taskNewMdl = $taskNewMdl->where('user_id', $params['user_id']);
                    }
                    if (isset($params['create_time']) && !empty($params['create_time'])){
                        $taskNewMdl = $taskNewMdl->whereBetween('create_time', $params['create_time']);
                    }
                    $count = $taskNewMdl->count();
                    if (isset($params['limit']) && isset($params['page'])){
                        $limit = $params['limit'] ?? 30;
                        $page = $params['page'] ?? 1;
                        $offset = $limit * ($page-1);
                        $taskNewMdl = $taskNewMdl->limit($limit)->offset($offset);
                    }
                    $taskNewMdl = $taskNewMdl->orderBy('create_time', 'DESC')->get();
                    foreach ($taskNewMdl as $item){
                        $item->user_name = $this->GetUsers($item->user_id)['account'] ?? '';
                        if ($item->feedback_type == 1){
                            $item->feedback_content = $item->feedback_content ?? '';
                        }else{
                            $item->feedback_content = $item->feedback_content ?? '';
                        }
                        if (!empty($item->feedback_content2)){
                            $item->feedback_content2 = json_decode($item->feedback_content2, true);
                        }else{
                            $item->feedback_content2 = [];
                        }
                    }
                    $list = $taskNewMdl;
                    break;
                case 4:
                    break;
                default:
                    throw new \Exception('未预设的场景值！');
            }

            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count ?? 0, 'list' => $list ?? []]];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function getTaskModel($params){
        $data = DB::table('tasks_model')->get()->toArray();
        return ['code' => 200, 'msg' => '获取成功','data'=>$data];
    }

    public function saveTasksSonScore($params)
    {
        try {
            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    if($users){
                        $params['user_id'] = $users->Id;
                    }else{
                        throw new \Exception('未给定创建人标识！');
                    }
                }else{
                    throw new \Exception('未给定创建人标识！');
                }
            }

            if (!isset($params['score']) || $params['score'] < 0 || $params['score'] > 100){
                throw new \Exception('未给定0-100以内的分数！');
            }

            if (!isset($params['task_son_id']) || empty($params['task_son_id'])){
                throw new \Exception('未给定任务标识！');
            }

            $taskSonMdl = db::table('tasks_son')
                ->where('Id', $params['task_son_id'])
                ->first();
            if (empty($taskSonMdl)){
                throw new \Exception('任务数据不存在！');
            }

            $save = [
                'task_son_id' => $taskSonMdl->Id,
                'task_id' => $taskSonMdl->task_id,
                'score' => $params['score'],
                'user_id' => $params['user_id'],
                'created_at' => date('Y-m-d H:i:s', microtime(true))
            ];

            $id = db::table('tasks_son_score')
                ->insertGetId($save);
            if (empty($id)){
                throw new \Exception('新增失败！');
            }
            return ['code' => 200, 'msg' => '评分成功！'];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '评分失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function copyTasks($params)
    {
        try {
            if (!isset($params['id']) || empty($params['id'])){
                throw new \Exception('未给定任务id!');
            }
            $taksMdl = db::table('tasks as a')
                ->leftJoin('task_class as b', 'a.class_id', '=', 'b.id')
                ->where('a.Id', $params['id'])
                ->select('a.Id', 'a.is_deleted', 'b.is_task', 'b.title as task_class_name')
                ->first();
            if (empty($taksMdl)){
                throw new \Exception("任务不存在！");
            }
            if ($taksMdl->is_task == 2){
                throw new \Exception($taksMdl->task_class_name."类型任务不可重发！");
            }

            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['task_id' => $taksMdl->Id]];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage()];
        }
    }
}



